package cn.fldong.controller;

import cn.fldong.model.Course;
import cn.fldong.service.CourseService;
import cn.fldong.service.impl.CourseServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/courses")
public class CourseServlet extends HttpServlet {
    private CourseService courseService;

    @Override
    public void init() throws ServletException {
        courseService = new CourseServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String action = request.getParameter("action");
        if (action == null) action = "list";

        try {
            switch (action) {
                case "list":
                    listCourses(request, response);
                    break;
                case "addPage":
                    request.getRequestDispatcher("/WEB-INF/views/course/add.jsp").forward(request, response);
                    break;
                case "add":
                    addCourse(request, response);
                    break;
                case "editPage":
                    editPage(request, response);
                    break;
                case "update":
                    updateCourse(request, response);
                    break;
                case "delete":
                    deleteCourse(request, response);
                    break;
                case "search":
                    searchCourses(request, response);
                    break;
                default:
                    listCourses(request, response);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("errorMsg", "系统错误：" + e.getMessage());
            request.getRequestDispatcher("/WEB-INF/views/error.jsp").forward(request, response);
        }
    }

    private void listCourses(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        List<Course> courses = courseService.getAllCourses();
        request.setAttribute("courses", courses);
        request.getRequestDispatcher("/WEB-INF/views/course/list.jsp").forward(request, response);
    }

    private void addCourse(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        String courseId = request.getParameter("courseId");
        String courseName = request.getParameter("courseName");
        String semester = request.getParameter("semester");
        String creditStr = request.getParameter("credit");
        BigDecimal credit = new BigDecimal(creditStr);

        if (courseService.courseNameExists(courseName)) {
            request.setAttribute("errorMsg", "课程名称已存在");
            Course course = new Course();
            course.setCourseId(courseId);
            course.setCourseName(courseName);
            course.setSemester(semester);
            course.setCredit(credit);
            request.setAttribute("course", course);
            request.getRequestDispatcher("/WEB-INF/views/course/add.jsp").forward(request, response);
            return;
        }

        Course course = new Course();
        course.setCourseId(courseId);
        course.setCourseName(courseName);
        course.setSemester(semester);
        course.setCredit(credit);

        boolean success = courseService.addCourse(course);
        if (success) {
            request.setAttribute("successMsg", "课程添加成功");
            listCourses(request, response);
        } else {
            request.setAttribute("errorMsg", "课程添加失败");
            request.setAttribute("course", course);
            request.getRequestDispatcher("/WEB-INF/views/course/add.jsp").forward(request, response);
        }
    }

    private void editPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        String courseId = request.getParameter("courseId");
        Course course = courseService.getCourseById(courseId);
        request.setAttribute("course", course);
        request.getRequestDispatcher("/WEB-INF/views/course/edit.jsp").forward(request, response);
    }

    private void updateCourse(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        String courseId = request.getParameter("courseId");
        String courseName = request.getParameter("courseName");
        String semester = request.getParameter("semester");
        String creditStr = request.getParameter("credit");
        BigDecimal credit = new BigDecimal(creditStr);

        Course existingCourse = courseService.getCourseById(courseId);
        if (!existingCourse.getCourseName().equals(courseName) && courseService.courseNameExists(courseName)) {
            request.setAttribute("errorMsg", "课程名称已存在");
            Course course = new Course();
            course.setCourseId(courseId);
            course.setCourseName(courseName);
            course.setSemester(semester);
            course.setCredit(credit);
            request.setAttribute("course", course);
            request.getRequestDispatcher("/WEB-INF/views/course/edit.jsp").forward(request, response);
            return;
        }

        Course course = new Course();
        course.setCourseId(courseId);
        course.setCourseName(courseName);
        course.setSemester(semester);
        course.setCredit(credit);

        boolean success = courseService.updateCourse(course);
        if (success) {
            request.setAttribute("successMsg", "课程更新成功");
            listCourses(request, response);
        } else {
            request.setAttribute("errorMsg", "课程更新失败");
            request.setAttribute("course", course);
            request.getRequestDispatcher("/WEB-INF/views/course/edit.jsp").forward(request, response);
        }
    }

    private void deleteCourse(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        String courseId = request.getParameter("courseId");
        boolean success = courseService.deleteCourse(courseId);

        if (success) {
            request.setAttribute("successMsg", "课程删除成功");
        } else {
            request.setAttribute("errorMsg", "课程删除失败");
        }

        listCourses(request, response);
    }

    private void searchCourses(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        String courseName = request.getParameter("courseName");
        String semester = request.getParameter("semester");

        List<Course> courses;
        if (semester != null && !semester.isEmpty()) {
            courses = courseService.getCoursesBySemester(semester);
        } else if (courseName != null && !courseName.isEmpty()) {
            courses = courseService.getCoursesByName(courseName);
        } else {
            courses = courseService.getAllCourses();
        }

        request.setAttribute("courses", courses);
        request.setAttribute("searchCourseName", courseName);
        request.setAttribute("searchSemester", semester);
        request.getRequestDispatcher("/WEB-INF/views/course/list.jsp").forward(request, response);
    }
}